package com.xy.job.admin.event

import com.xy.job.admin.core.schedule.Scheduler
import com.xy.job.admin.core.schedule.TriggerTask
import com.xy.job.admin.repository.JobInstanceRepository
import com.xy.job.admin.repository.NodeRegistryRepository
import org.springframework.context.event.EventListener
import org.springframework.stereotype.Component
import java.time.LocalDateTime

@Component
class JobInstanceCreateEventListener(
    var scheduler: Scheduler,
    var nodeRegistryRepository: NodeRegistryRepository,
    var jobInstanceRepository: JobInstanceRepository,
) {

    @EventListener
    fun handleEvent(event: JobInstanceCreateEvent) {
        val jobInstance = event.jobInstance
        val triggerTask = TriggerTask(
            jobInstance = jobInstance,
            jobInstanceRepository = jobInstanceRepository,
            nodeRegistryRepository = nodeRegistryRepository,
        )
        val scheduleAt = jobInstance.scheduleTime ?: LocalDateTime.now()
        scheduler.addTask(jobInstance.jobName!!, scheduleAt, triggerTask)
    }
}